package cn.edu.pzhu.javaweb.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class OnlineListener implements HttpSessionAttributeListener {

    private  int online = 0;

    public OnlineListener() {}

    public void attributeAdded(HttpSessionBindingEvent se) {
        if (se.getName().equals("username")) {//只有登录才会操作username
            synchronized (OnlineListener.class) {
                Object object = se.getSession().getServletContext().getAttribute("online");
                if (object == null) {
                    online = 1;
                }else {
                    online = (Integer)object + 1;
                }
                System.out.println("有新用户"+se.getValue()+"登录了系统，当前在线人数为"+online);
                se.getSession().getServletContext().setAttribute("online", online);

            }
        }
    }

    public void attributeRemoved(HttpSessionBindingEvent se) {
        if (se.getName().equals("username")) {//只有登录才会操作username
            synchronized (OnlineListener.class) {
                Object object = se.getSession().getServletContext().getAttribute("online");
                if (object == null) {
                    online = 0;
                }else {
                    online = (Integer)object - 1;
                }
                System.out.println("用户"+se.getValue()+"退出了系统，当前在线人数为"+online);
                se.getSession().getServletContext().setAttribute("online", online);

            }
        }
    }

    public void attributeReplaced(HttpSessionBindingEvent se) {}
}
